import { getToken, setToken, removeToken } from '@/utils/auth'
import moment from "moment";

const defaultAvatar = require('@/assets/images/profile.jpg')
const getDefaultState = () => {
  return {
    // token: localStorage.getItem('_token') ? localStorage.getItem('_token') : null,
    token: getToken(),
    name: localStorage.getItem('name') ? localStorage.getItem('name') : '',
    avatar: localStorage.getItem('avatar') ? localStorage.getItem('avatar') : defaultAvatar
  }
}
const state = getDefaultState()


const mutations = {
  SET_TOKEN: (state, token) => {
    setToken(token)
    state.token = token
  },
  SET_NAME: (state, name) => {
    localStorage.setItem("name", name)
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    // console.log(avatar)
    // let url = defaultAvatar
    // if (avatar && avatar.length) {
    //   url = avatar
    // }
    state.avatar = avatar
  },
  REMOVE_DATA: (state) => {
    state.token = null
    removeToken()
    localStorage.removeItem('name')
    state.name = ""
    // state.avatar = ""
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      try {
        commit('SET_TOKEN', moment().valueOf())
        commit('SET_NAME', username.trim())
        resolve()
      } catch {
        reject()
      }
    })
  },
  logout({ commit }) {
    commit('REMOVE_DATA') // must remove  token  first
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}